/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制
 */
package co.yixiang.modules.shop.service.impl;

import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.modules.shop.domain.YxStoreCart;
import co.yixiang.modules.shop.domain.YxStoreProductAttrResult;
import co.yixiang.modules.shop.domain.YxStoreProductAttrValue;
import co.yixiang.modules.shop.service.*;
import co.yixiang.modules.shop.service.dto.*;
import co.yixiang.modules.shop.service.mapper.StoreCartMapper;
import co.yixiang.utils.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
 * @author hupeng
 * @date 2020-05-12
 */
@Service
@AllArgsConstructor
//@CacheConfig(cacheNames = "yxStoreCart")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxStoreCartServiceImpl extends BaseServiceImpl<StoreCartMapper, YxStoreCart> implements YxStoreCartService {

    private final IGenerator generator;

    private final StoreCartMapper storeCartMapper;
    @Autowired
    private YxStoreOnlineService storeOnlineService;
    @Autowired
    private YxStoreProductAttrValueService attrValueService;

    @Autowired
    private YxStoreProductAttrResultService attrResultService;



    @Override
    public List<ShopCartDto> getOnesCartItems(Long uid) {
        List<YxStoreCart> cartList = list(new LambdaQueryWrapper<YxStoreCart>().eq(YxStoreCart::getUid, uid));
        return convertCartItem(cartList);
    }

    /**
     * 将购物车项列表转为ShopCartDto列表
     * @param cartList
     * @return
     */
    public List<ShopCartDto> convertCartItem(List<YxStoreCart> cartList){
        HashSet<Long> storeIds = new HashSet<>();
        for (YxStoreCart yxStoreCart : cartList) {
            storeIds.add(yxStoreCart.getStoreId());
        }
        //storeId对应ShopCartDto
        HashMap<Long, ShopCartDto> map = new HashMap<>();
        for (Long storeId : storeIds) {
            ShopCartDto shopCartDto = new ShopCartDto();
            shopCartDto.setShopId(storeId);
            shopCartDto.setShopName(storeOnlineService.getById(storeId).getName());
            map.put(storeId,shopCartDto);
        }

        for (YxStoreCart cart : cartList) {
            //设置sku
            YxStoreCartDto dto = generator.convert(cart, YxStoreCartDto.class);
            YxStoreProductAttrValue attrValue = attrValueService.getOne(new LambdaQueryWrapper<YxStoreProductAttrValue>()
                    .eq(YxStoreProductAttrValue::getSkuValue, dto.getProductAttrUnique()));
            dto.setSku(attrValue);

            //设置skus
            YxStoreProductAttrResult attrResult = attrResultService.getOne(new LambdaQueryWrapper<YxStoreProductAttrResult>()
                    .eq(YxStoreProductAttrResult::getProductId, dto.getProductId()));
            ShopCartItemDto shopCartItemDto = new ShopCartItemDto();
            shopCartItemDto.setStoreCartDto(dto);
            shopCartItemDto.setSkus(attrResult);

            //添加到对应ShopCartDto中
            Long storeId = dto.getStoreId();
            ShopCartDto shopCartDto = map.get(storeId);
            shopCartDto.getShopCartItemDtos().add(shopCartItemDto);

        }
        return new ArrayList<>(map.values());
    }

    @Override
    public List<YxStoreCartDto> listPreSubmit(YxStoreCartQueryCriteria criteria) {
        List<YxStoreCart> list = list(new LambdaQueryWrapper<YxStoreCart>().eq(YxStoreCart::getIsNew, 1)
                .eq(YxStoreCart::getUid,criteria.getUid()));
    //    没有地址时，运费不显示
        List<YxStoreCartDto> convert = generator.convert(list, YxStoreCartDto.class);
        for (YxStoreCartDto dto : convert) {
        //暂时使用假的运费模板
            ExpressPlanDto e = new ExpressPlanDto();
            e.setId(1);
            e.setName("方案1");
            e.setStoreId(12);
            e.setIsCountry(1);
            e.setType(2);
            dto.setExpressPlanDto(e);
        }
        return convert;
    }

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(YxStoreCartQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<YxStoreCart> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), YxStoreCartDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<YxStoreCart> queryAll(YxStoreCartQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(YxStoreCart.class, criteria));
    }


    @Override
    public void download(List<YxStoreCartDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YxStoreCartDto yxStoreCart : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户ID", yxStoreCart.getUid());
            map.put("类型", yxStoreCart.getType());
            map.put("商品ID", yxStoreCart.getProductId());
            map.put("商品属性", yxStoreCart.getSku().getSkuValue());
            map.put("商品数量", yxStoreCart.getCartNum());
            map.put("0 = 未购买 1 = 已购买", yxStoreCart.getIsPay());
            map.put("是否为立即购买", yxStoreCart.getIsNew());
            map.put("拼团id", yxStoreCart.getCombinationId());
            map.put("秒杀产品ID", yxStoreCart.getSeckillId());
            map.put("砍价id", yxStoreCart.getBargainId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<CountDto> findCateName() {
        return storeCartMapper.findCateName();
    }
}
